package com.ypf.rpc;

import com.ypf.rpc.annotation.RpcServerScan;
import com.ypf.rpc.manager.server.RpcServiceManager;
import com.ypf.rpc.message.RpcQueryRegisterRequestMessage;
import com.ypf.rpc.message.RpcRegisterRequestMessage;
import com.ypf.rpc.nettyHandler.RpcQueryRegisterResponseMessageHandler;
import com.ypf.rpc.procotol.MessageCodecSharable;
import com.ypf.rpc.procotol.ProcotolFrameDecoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.net.InetSocketAddress;

@RpcServerScan
public class test {
    public static void main(String[] args) {
        // 日志handler
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);

        // 消息处理handler
        MessageCodecSharable MESSAGE_CODE = new MessageCodecSharable();

        // 自定义查询服务返回消息处理器
        RpcQueryRegisterResponseMessageHandler RPC_QUERY_REGISTER_RESPONSE_HANDLER = new RpcQueryRegisterResponseMessageHandler();

        try {
            ChannelFuture channelFuture = new Bootstrap().group(new NioEventLoopGroup())
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            // 定长解码器
                            socketChannel.pipeline().addLast(new ProcotolFrameDecoder());
                            socketChannel.pipeline().addLast(MESSAGE_CODE);
                            socketChannel.pipeline().addLast(RPC_QUERY_REGISTER_RESPONSE_HANDLER);
                        }
                    }).connect(new InetSocketAddress("127.0.0.1",10001)).sync();
            Channel channel = channelFuture.channel();

            RpcQueryRegisterRequestMessage rpcRegisterRequestMessage = new RpcQueryRegisterRequestMessage();
            rpcRegisterRequestMessage.setServerName("com.ypf.rpc.service.HelloService2Impl");
            channel.writeAndFlush(rpcRegisterRequestMessage);

            channel.closeFuture().sync();  // 同步等待关闭阻塞 此线程将会在这阻塞

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
